package com.yapmadanolme.dao;

import com.yapmadanolme.model.User;
import java.sql.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author Mehmet
 */
public class UsersDao extends HttpServlet
{
     Connection connection;

     @Override
     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     {
        int command = Integer.parseInt(request.getParameter("type"));
        HttpSession session = request.getSession();
        String param = request.getParameter("name");
        int id= Integer.parseInt(request.getParameter("id"));
        PrintWriter out=response.getWriter();
        switch(command)
        {
            case 1: //login user
                if(!selectUser(id))
                {
                    insertUser(param,id);
                    out.println("user signed up");
                }
                else
                    out.println("user logged in");
                break;
            case 2: //get all User from database
                List<User> userList=getUsers();
                Iterator iter = userList.iterator();
                while(iter.hasNext())
                {
                  User user = (User) iter.next();
                  out.println(user.getUserId()+" "+user.getName()+" "+user.getSurName());
                }
                break;
        }
     }
    public void openConnection()// opens Database connection
    {
        String dbUrl = "jdbc:mysql://localhost:3306/yapmadanolmedb";
        String username = "root";
        String password ="1";

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(dbUrl, username,password);

        } //end try
        catch(ClassNotFoundException e) { e.printStackTrace();   }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
    public void closeConnection()//closes database connection
    {
        try {
            connection.close();
        } catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private boolean selectUser(int id)
    {
        String query="select * from users where userID=?";
        openConnection();
        try {
            PreparedStatement stmt=connection.prepareStatement(query);
            stmt.setInt(1, id);
            ResultSet rs=stmt.executeQuery();
            rs.last();
            return rs.getRow()==1;
        } catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

     private boolean  insertUser(String param,int id)
     {
         String name,surname;

         name=param.split(" ")[0];
         surname=param.split(" ")[1];
         int res=0;
         String query="insert into users (userID, name , surname) Values (?,?,?)";
         openConnection();
         try {
            PreparedStatement stmt=null;
            stmt=connection.prepareStatement(query);
            stmt.setInt(1, id);
            stmt.setString(2,name);
            stmt.setString(3,surname);
            res=stmt.executeUpdate();
            stmt.close();
        }
         catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        closeConnection();
        return res==1;
     }

    public List getUsers()
    {
        String query="select * from users";
        List<User> result=new ArrayList();
        openConnection();
        try {
            Statement stmt=null;
            stmt=connection.createStatement();
            ResultSet rs=stmt.executeQuery(query);
            while (rs.next()) {
                User newUser = new User();
                newUser.setUserId(rs.getInt("userID"));
                newUser.setName(rs.getString("name"));
                newUser.setSurName(rs.getString("surname"));
                result.add(newUser);
            }
            rs.close();
            stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        closeConnection();
        return result;
    }


}  
